<template>
  <div id="app">
    <el-row :gutter="20" style="height: 100%">
      <!-- 左侧部门树 -->
      <el-col v-show="isShow" :span="4" :xs="24" style="height: 100%">
        <ContentWrap class="h-full">
          <MaterialTree
            ref="materialTreeRef"
            @node-click="handleNodeClick"
            @refresh-list="handleRefreshList"
            @refresh-material-class="getMaterialClassList"
            :typeInfo="typeInfo"
          />
        </ContentWrap>
      </el-col>
      <el-col :span="20" :xs="24" style="height: 100%">
        <!-- 标签页和搜索工作栏 -->
        <ContentWrap>
          <el-tabs v-model="activeTab">
            <el-tab-pane :label="`全部(${typeCountMap.all || 0})`" name="all" />
            <el-tab-pane :label="`视频(${typeCountMap.video || 0})`" name="video" />
            <el-tab-pane :label="`音频(${typeCountMap.audio || 0})`" name="audio" />
            <el-tab-pane :label="`文档(${typeCountMap.document || 0})`" name="document" />
            <el-tab-pane :label="`图片(${typeCountMap.image || 0})`" name="image" />
            <el-tab-pane :label="`压缩包(${typeCountMap.archive || 0})`" name="archive" />
          </el-tabs>

          <el-form
            ref="queryFormRef"
            :inline="true"
            :model="queryParams"
            class="-mb-15px mt-0px"
            label-width="68px"
          >
            <el-form-item label="文件名称" prop="name">
              <el-input
                v-model="queryParams.name"
                class="!w-240px"
                clearable
                placeholder="请输入文件名称"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="创建时间" prop="createTime">
              <el-date-picker
                v-model="queryParams.createTime"
                class="!w-240px"
                end-placeholder="结束日期"
                start-placeholder="开始日期"
                type="datetimerange"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery">
                <Icon class="mr-5px" icon="ep:search" />
                搜索
              </el-button>
              <el-button @click="resetQuery">
                <Icon class="mr-5px" icon="ep:refresh" />
                重置
              </el-button>
              <el-button
                v-hasPermi="['course:material:create']"
                plain
                type="primary"
                @click="openForm('create')"
              >
                <Icon class="mr-5px" icon="ep:plus" />
                新增
              </el-button>
              <el-button
                v-hasPermi="['course:material:export']"
                :loading="exportLoading"
                plain
                type="success"
              >
                <Icon class="mr-5px" icon="ep:download" />
                导出
              </el-button>
              <el-button v-if="activeTab !== 'all'" type="primary" @click="handleUpload">
                <Icon class="mr-5px" icon="ep:upload" />
                上传{{ getUploadButtonText() }}
              </el-button>
            </el-form-item>
          </el-form>
        </ContentWrap>

        <!-- 列表 -->
        <ContentWrap class="h-full-list">
          <TreeToggleButton v-model:isShow="isShow" />
          <el-table
            ref="tableRef"
            v-loading="loading"
            :data="list"
            :show-overflow-tooltip="true"
            :stripe="true"
            @selection-change="handleSelectionChange"
          >
            <el-table-column v-if="showSelection" align="center" type="selection" width="55" />
            <el-table-column align="center" label="id" prop="id" width="80" />
            <el-table-column
              :show-overflow-tooltip="true"
              align="left"
              label="文件名称"
              min-width="130"
              prop="name"
            />
            <el-table-column align="center" label="文件类型" prop="fileType" width="80">
              <template #default="scope">
                <Icon :icon="getFileTypeIcon(scope.row.fileType)" class="text-lg" />
              </template>
            </el-table-column>
            <el-table-column align="center" label="文件目录" prop="materialId">
              <template #default="scope">
                {{ getMaterialClassName(scope.row.materialId) }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="文件大小" prop="fileSize" width="90" />
            <el-table-column align="center" label="课件时长" prop="fileTime" width="80" />
            <el-table-column align="center" label="创建时间" prop="createTime" width="200px">
              <template #default="scope">
                <div style="text-align: center">{{ formatDate(scope.row.createTime) }}</div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" min-width="100px">
              <template #default="scope">
                <el-button link type="primary" @click="handlePreview(scope.row)">
                  <Icon class="mr-5px" icon="ep:view" />
                  预览
                </el-button>
                <el-button
                  v-hasPermi="['course:material:update']"
                  link
                  type="primary"
                  @click="handleEdit(scope.row)"
                >
                  <Icon class="mr-5px" icon="ep:edit" />
                  编辑
                </el-button>
                <el-button
                  v-hasPermi="['course:material:delete']"
                  link
                  type="danger"
                  @click="handleDelete(scope.row.id)"
                >
                  <Icon class="mr-5px" icon="ep:delete" />
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <Pagination
            v-model:limit="queryParams.pageSize"
            v-model:page="queryParams.pageNo"
            :total="total"
            class="mt-10px"
            @pagination="getList"
          />
        </ContentWrap>
      </el-col>
    </el-row>

    <!-- 上传/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      append-to-body
      destroy-on-close
      width="500px"
    >
      <el-form
        v-if="dialogVisible"
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item v-if="!form.id" label="选择文件" prop="fileList">
          <el-upload
            ref="uploadRef"
            v-model:file-list="form.fileList"
            :auto-upload="false"
            :before-change="handleBeforeChange"
            :on-change="handleFileChange"
            action=""
            class="upload-demo"
            drag
            multiple
          >
            <Icon icon="ep:upload" />
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <template #tip>
              <div class="upload-tips">
                <div>支持批量上传</div>
                <div>{{ getUploadTips() }}</div>
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="文件名称" prop="name">
          <el-input
            v-model="form.name"
            :title="form.name"
            class="filename-input"
            placeholder="请输入文件名称"
          />
        </el-form-item>
        <el-form-item label="文件目录" prop="materialId">
          <el-tree-select
            v-model="form.materialId"
            :check-strictly="true"
            :data="materialClassList"
            :props="{
              label: 'name',
              value: 'id',
              children: 'children'
            }"
            class="!w-240px"
            clearable
            placeholder="请选择文件目录"
          />
        </el-form-item>
        <el-form-item label="课件时长" prop="fileTime">
          <el-input v-model="form.fileTime" placeholder="请输入课件时长" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleFormSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { computed, nextTick, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
import { ElMessage, ElMessageBox, UploadUserFile } from 'element-plus'
import MaterialTree from '../compont/TypeTree.vue'
import * as MaterialApi from '@/api/material/course'
import { useCentreStore } from '@/store/modules/lession/centre'
import { storeToRefs } from 'pinia'
import TreeToggleButton from '@/components/TreeToggleButton/index.vue'

const isShow = ref(true) // 列表的加载中// 数据类型定义
interface Material {
  id: number
  name: string
  fileType: number // 1:视频 2:文档 3:音频 4:图片 5:压缩包
  materialId: number
  fileSize: number
  fileTime: number
  createTime: string
}

interface MaterialClass {
  id: number
  name: string
  parentId: number
  children?: MaterialClass[]
}

interface QueryParams {
  pageNo: number
  pageSize: number
  name?: string
  fileType?: number
  materialId?: number[]
  createTime?: string[]
}

interface UploadFile {
  raw: File
  name: string

  [key: string]: any
}

interface FormData {
  id?: number
  name: string
  materialId?: number
  fileTime?: string
  fileList: UploadUserFile[]
}

// 组件定义
defineOptions({ name: 'Material' })

// 状态定义
const total = ref(0)
const list = ref<Material[]>([])
const loading = ref(false)
const exportLoading = ref(false)
const activeTab = ref('all')
const typeCountMap = ref<Record<string, number>>({})
const dialogVisible = ref(false)
const dialogType = ref<'create' | 'update'>('create')
const queryFormRef = ref()
const typeInfo = ref({
  typeName: '文件目录',
  type: 1
})
const formRef = ref()
const uploadRef = ref()
const materialTreeRef = ref()
const materialClassList = ref<MaterialClass[]>([])

// 添加 store 的初始化
const centreStore = useCentreStore()

// 使用 storeToRefs 来保持响应性
const { selectedMaterials } = storeToRefs(centreStore)

// 查询参数
const queryParams = reactive<QueryParams>({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  fileType: undefined,
  materialId: undefined,
  createTime: []
})

// 表单数据
const form = reactive<FormData>({
  id: undefined,
  name: '',
  materialId: undefined,
  fileTime: undefined,
  fileList: []
})

// 文件类型相关映射
const fileTypeMap = {
  // 文件类型对应的标签页名称
  tabNames: {
    video: 1,
    document: 2,
    audio: 3,
    image: 4,
    archive: 5
  },
  // 文件类型对应的图标
  icons: {
    1: 'ep:video-camera',
    2: 'ep:document',
    3: 'ep:headset',
    4: 'ep:picture',
    5: 'ep:folder'
  },
  // 文件类型对应的扩展名
  extensions: {
    video: ['mp4', 'avi', 'mov'],
    document: ['doc', 'docx', 'pdf', 'ppt', 'pptx', 'xls', 'xlsx'],
    audio: ['mp3', 'wav', 'ogg'],
    image: ['jpg', 'jpeg', 'png', 'gif'],
    archive: ['zip', 'rar', '7z']
  },
  // 文件类型对应的上传提示
  uploadTips: {
    video: '支持格式：mp4、avi、mov等视频格式，单个文件最大支持1GB',
    document: '支持格式：doc、docx、pdf、ppt、pptx、xls、xlsx等文档格式，单个文件最大支持100MB',
    audio: '支持格式：mp3、wav、ogg等音频格式，单个文件最大支持500MB',
    image: '支持格式：jpg、jpeg、png、gif等图片格式，单个文件最大支持10MB',
    archive: '支持格式：zip、rar、7z等压缩包格式，单个文件最大支持500MB'
  }
}

// 计算属性：对话框标题
const dialogTitle = computed(() => {
  if (dialogType.value === 'create') {
    return `上传${getUploadButtonText()}`
  }
  return '编辑文件'
})

// 表单校验规则
const formRules = {
  fileList: [
    {
      required: true,
      message: '请选择上传文件',
      trigger: 'change',
      validator: (rule: any, value: any[]) => {
        if (form.id) return true // 编辑时不校验文件
        return value?.length > 0
      }
    }
  ],
  name: [{ required: true, message: '请输入文件名称', trigger: 'blur' }],
  materialId: [{ required: true, message: '请选择文件目录', trigger: 'change' }]
}

// 监听标签页变化
watch(activeTab, (newVal) => {
  queryParams.fileType = newVal === 'all' ? undefined : fileTypeMap.tabNames[newVal]
  handleQuery()
})

/** 获取文件类型图标 */
const getFileTypeIcon = (fileType: number): string => {
  return fileTypeMap.icons[fileType] || 'ep:document'
}

/** 获取上传按钮文本 */
const getUploadButtonText = () => {
  const textMap = {
    all: '文件',
    video: '视频',
    document: '文档',
    audio: '音频',
    image: '图片',
    archive: '压缩包'
  }
  return textMap[activeTab.value]
}

/** 获取上传提示文本 */
const getUploadTips = () => {
  return fileTypeMap.uploadTips[activeTab.value] || ''
}

/** 格式化时间戳 */
const formatDate = (timestamp: string | number) => {
  if (!timestamp) return ''
  const date = new Date(Number(timestamp))
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

/** 根据目录ID获取目录名称 */
const getMaterialClassName = (materialId: number) => {
  const findName = (list: MaterialClass[]) => {
    for (const item of list) {
      if (item.id === materialId) return item.name
      if (item.children) {
        const name = findName(item.children)
        if (name) return name
      }
    }
    return ''
  }
  return findName(materialClassList.value) || '-'
}

// 添加一个标志来控制是否处理 selection change 事件
const isInitializing = ref(true)

/** 查询列表数据 */
const getList = async () => {
  loading.value = true
  try {
    console.log('查询参数:', queryParams)
    const data = await MaterialApi.getMaterialPage(queryParams)
    list.value = data.list
    total.value = data.total

    // 在数据加载完成后，根据 selectedMaterials 设置选中状态
    nextTick(async () => {
      isInitializing.value = true // 设置标志，禁止处理 selection change

      // 清除所有选中状态
      // 设置当前页面中应该选中的行
      for (const row of list.value) {
        if (selectedMaterials.value.some((selected) => selected.id === row.id)) {
          await nextTick() // 等待 DOM 更新
          tableRef.value?.toggleRowSelection(row, true)
        }
      }

      // 确保所有选择操作完成后再允许处理 selection change
      setTimeout(() => {
        isInitializing.value = false
      }, 100)
    })
  } finally {
    loading.value = false
  }
}

/** 获取文件类型数量 */
const getTypeCount = async () => {
  try {
    // 构造查询参数
    const params = {
      name: queryParams.name,
      materialId: queryParams.materialId || [0],
      createTime: queryParams.createTime || []
    }
    const countMap = await MaterialApi.getFileTypeCount(params)
    typeCountMap.value = {
      all: countMap['0'] || 0,
      video: countMap['1'] || 0,
      document: countMap['2'] || 0,
      audio: countMap['3'] || 0,
      image: countMap['4'] || 0,
      archive: countMap['5'] || 0
    }
  } catch (error) {
    console.error('获取文件类型数量失败:', error)
  }
}

/** 获取目录列表 */
const getMaterialClassList = async () => {
  try {
    const type = typeInfo.value.type
    const data = await MaterialApi.getMaterialClassList(type)
    if (Array.isArray(data)) {
      materialClassList.value = convertToTreeData(data)
    } else {
      console.error('获取到的目录列表数据格式不正确:', data)
      materialClassList.value = []
    }
  } catch (error) {
    console.error('获取目录列表失败:', error)
    materialClassList.value = []
    ElMessage.error('获取目录列表失败')
  }
}

/** 将平铺结构转换为树形结构 */
const convertToTreeData = (list: MaterialClass[]) => {
  if (!list || list.length === 0) return []

  const map = new Map()
  const result: MaterialClass[] = []

  // 首先创建所有节点的副本
  list.forEach((item) => {
    map.set(item.id, {
      ...item,
      children: [],
      // 确保基本属性都存在
      id: item.id || 0,
      name: item.name || '',
      parentId: item.parentId || 0
    })
  })

  // 构建树形结构
  list.forEach((item) => {
    const node = map.get(item.id)
    if (!node) return

    if (!item.parentId || item.parentId === 0) {
      result.push(node)
    } else {
      const parent = map.get(item.parentId)
      if (parent) {
        if (!parent.children) parent.children = []
        parent.children.push(node)
      } else {
        // 如果找不到父节点，作为顶级节点处理
        result.push(node)
      }
    }
  })

  return result
}

/** 处理查询操作 */
const handleQuery = async () => {
  try {
    queryParams.pageNo = 1
    loading.value = true
    // 同时刷新列表和类型统计
    await Promise.all([getList(), getTypeCount()])
  } catch (error) {
    console.error('查询失败:', error)
    ElMessage.error('查询失败')
  } finally {
    loading.value = false
  }
}

/** 处理重置操作 */
const resetQuery = async () => {
  try {
    queryFormRef.value.resetFields()
    queryParams.materialId = undefined
    loading.value = true
    // 同时刷新列表和类型统计
    await Promise.all([getList(), getTypeCount()])
  } catch (error) {
    console.error('重置查询失败:', error)
    ElMessage.error('重置查询失败')
  } finally {
    loading.value = false
  }
}

/** 处理删除操作 */
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm('是否确认删除？', '警告', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })

    await MaterialApi.deleteMaterial(id)
    ElMessage.success('删除成功')
    await Promise.all([getList(), getTypeCount()])
  } catch (error) {
    console.error('删除失败:', error)
  }
}

/** 打开表单 */
const openForm = async (type: 'create' | 'update', id?: number) => {
  dialogType.value = type
  resetForm()

  // 每次打开表单时重新初始化
  await getMaterialClassList()
  await getTypeCount()

  if (type === 'update' && id) {
    const data = await MaterialApi.getMaterial(id)
    form.id = data.id
    form.name = data.name
    form.materialId = data.materialId
    form.fileTime = data.fileTime
  }

  dialogVisible.value = true
}

/** 重置表单 */
const resetForm = () => {
  form.id = undefined
  form.name = ''
  form.materialId = undefined
  form.fileTime = undefined
  form.fileList = []
  formRef.value?.resetFields()
  uploadRef.value?.clearFiles()
}

/** 处理表单提交 */
const handleFormSubmit = async () => {
  await formRef.value.validate()

  try {
    if (form.id) {
      // 编辑模式
      await MaterialApi.updateMaterial({
        id: form.id,
        name: form.name,
        materialId: form.materialId,
        fileTime: form.fileTime ? Number(form.fileTime) : undefined
      })
      ElMessage.success('修改成功')
    } else {
      // 上传模式
      const formData = new FormData()

      // 添加文件
      if (form.fileList?.length > 0) {
        form.fileList.forEach((file: any) => {
          formData.append('fileList', file.raw)
        })
      }

      // 添加其他参数
      formData.append('name', form.name)
      formData.append('fileType', String(fileTypeMap.tabNames[activeTab.value] || ''))
      formData.append('materialId', String(form.materialId || ''))
      if (form.fileTime) {
        formData.append('fileTime', form.fileTime)
      }

      await MaterialApi.uploadFile(formData)
      ElMessage.success('上传成功')
    }

    dialogVisible.value = false
    await Promise.all([getList(), getTypeCount()])
  } catch (error) {
    if (error === false) return
    console.error(form.id ? '修改失败:' : '上传失败:', error)
    ElMessage.error(form.id ? '修改失败' : '上传失败')
  }
}

/** 处理上传操作 */
const handleUpload = async () => {
  try {
    // 先获取最新目录列表
    await getMaterialClassList()

    // 重置表单
    resetForm()

    // 如果有当前选中的目录，使用它
    if (queryParams.materialId && queryParams.materialId.length > 0) {
      form.materialId = queryParams.materialId[0]
    }

    // 设置对话框类型
    dialogType.value = 'create'

    // 打开弹框
    dialogVisible.value = true
  } catch (error) {
    console.error('打开上传弹框失败:', error)
    ElMessage.error('打开上传弹框失败')
  }
}

/** 处理文件选择前的验证 */
const handleBeforeChange = (file: File) => {
  const ext = file.name.split('.').pop()?.toLowerCase()
  if (!ext) {
    ElMessage.error('文件格式不正确')
    return false
  }

  const allowedExts = fileTypeMap.extensions[activeTab.value]
  if (!allowedExts?.includes(ext)) {
    ElMessage.error(`请选择${getUploadButtonText()}格式的文件`)
    return false
  }

  return true
}

/** 处理文件选择变化 */
const handleFileChange = (file: any, fileList: any[]) => {
  const ext = file.name.split('.').pop()?.toLowerCase()
  if (!ext) {
    ElMessage.error('文件格式不正确')
    uploadRef.value?.clearFiles()
    return false
  }

  const allowedExts = fileTypeMap.extensions[activeTab.value]
  if (!allowedExts?.includes(ext)) {
    ElMessage.error(`请选择${getUploadButtonText()}格式的文件`)
    uploadRef.value?.clearFiles()
    return false
  }

  form.fileList = fileList
  if (fileList.length === 1) {
    form.name = file.name.replace(/\.[^/.]+$/, '')
  }
}

/** 递归获取所有子节点ID */
const getAllChildrenIds = (node: MaterialClass): number[] => {
  const ids: number[] = [node.id]
  if (node.children && node.children.length > 0) {
    node.children.forEach((child) => {
      ids.push(...getAllChildrenIds(child))
    })
  }
  return ids
}

/** 根据节点ID获取节点及其所有子节点 */
const getNodeAndChildren = (nodeId: number, list: MaterialClass[]): MaterialClass | null => {
  for (const item of list) {
    if (item.id === nodeId) {
      return item
    }
    if (item.children) {
      const found = getNodeAndChildren(nodeId, item.children)
      if (found) return found
    }
  }
  return null
}

/** 处理树节点点击 */
const handleNodeClick = async (materialId: number) => {
  console.log('父组件收到节点点击事件, ID:', materialId)
  // 获取当前节点
  const currentNode = getNodeAndChildren(materialId, materialClassList.value)
  if (currentNode) {
    console.log('找到当前节点:', currentNode)
    // 获取当前节点及其所有子节点的ID
    const allIds = getAllChildrenIds(currentNode)
    // 更新查询参数
    queryParams.materialId = allIds
    // 保存当前选中的节点ID到表单
    form.materialId = materialId
    // 重新查询列表和类型统计
    await Promise.all([
      getList(), // 刷新列表数据
      getTypeCount() // 刷新标签页数字
    ])
  } else {
    console.warn('未找到节点:', materialId)
  }
}

/** 处理编辑操作 */
const handleEdit = async (row: Material) => {
  dialogType.value = 'update'
  resetForm()

  // 先获取最新目录列表
  await getMaterialClassList()

  // 设置表单数据
  form.id = row.id
  form.name = row.name
  form.materialId = row.materialId
  form.fileTime = row.fileTime ? String(row.fileTime) : undefined

  // 打开弹框
  dialogVisible.value = true
}

/** 处理刷新列表 */
const handleRefreshList = async () => {
  // 重新获取列表和类型统计
  await Promise.all([getList(), getTypeCount()])
}

// 添加监听器
// 监听文件名称和创建时间的变化
watch(
  [() => queryParams.name, () => queryParams.createTime],
  ([newName, newTime], [oldName, oldTime]) => {
    // 只在值从有到无时触发刷新
    if (
      (oldName && !newName) || // 文件名称从有到无
      (oldTime?.length && (!newTime || newTime.length === 0)) // 创建时间从有到无
    ) {
      handleQuery()
    }
  },
  { deep: true }
)

/** 处理选择变化 */
const handleSelectionChange = (selection: any[]) => {
  if (!selection || selection.length === 0) {
    console.log('selection 为空')
    return
  }
  console.log('selection:', JSON.stringify(selection))

  // 如果正在初始化，不处理选择变化
  if (isInitializing.value) {
    console.log('初始化中，不处理选择变化')
    return
  }

  // 获取当前页面的所有ID
  const currentPageIds = new Set(list.value.map((item) => item.id))
  console.log('当前页面的所有ID:', JSON.stringify([...currentPageIds]))

  // 获取当前选中的 ID 集合（当前页面的选中项）
  const currentIds = new Set()
  selection.forEach((item) => {
    if (item && typeof item.id !== 'undefined') {
      currentIds.add(item.id)
    }
  })
  // console.log('当前选中的ID:', JSON.stringify([...currentIds]))

  // 获取之前选中的 ID 集合
  const previousIds = new Set(selectedMaterials.value.map((item) => item.id))
  // console.log('之前选中的ID:', JSON.stringify([...previousIds]))

  // 找出当前页面中被取消选中的 ID
  // 只处理当前页面上的，且之前是选中状态的 ID
  const removedIds = new Set(
    [...previousIds].filter((id) => currentPageIds.has(id) && !currentIds.has(id))
  )
  // console.log('被取消选中的ID:', JSON.stringify([...removedIds]))

  // 找出新增选中的 ID
  const addedIds = new Set([...currentIds].filter((id) => !previousIds.has(id)))
  // console.log('新增选中的ID:', JSON.stringify([...addedIds]))

  // 处理移除的材料
  if (removedIds.size > 0) {
    removedIds.forEach((id) => {
      console.log('正在移除材料，ID:', id)
      centreStore.removeMaterial(id)
    })
  }

  // 处理新增的材料
  if (addedIds.size > 0) {
    addedIds.forEach((id) => {
      const addedMaterial = selection.find((item) => item.id === id)
      if (addedMaterial) {
        console.log('正在添加材料:', addedMaterial)
        centreStore.addMaterial(addedMaterial)
      }
    })
  }
}

const emit = defineEmits(['selection-change'])
// 添加表格引用
const tableRef = ref()

// 添加 props 定义
defineProps({
  showSelection: {
    type: Boolean,
    default: false
  }
})

/** 初始化 */
onMounted(async () => {
  console.log('初始化')
  isInitializing.value = true // 设置初始化标志
  await getMaterialClassList()
  await getTypeCount()
  await handleQuery()
})

onUnmounted(() => {
  console.log('组件被关闭了')
  // 在这里执行清理操作，比如取消定时器、移除事件监听器等
})
</script>

<style scoped>
#app {
  /* 删除固定高度和溢出设置 */
  /* height: 86vh; */
  /* overflow: auto; */
}

:deep(.el-pagination) {
  margin-top: 15px;
  justify-content: flex-end;
}

.upload-tips {
  margin-top: 5px;
  color: #909399;
  font-size: 12px;
  line-height: 1.5;
}

.upload-tips div:first-child {
  margin-bottom: 2px;
}

/* 添加文件名输入框的样式 */
.filename-input :deep(.el-input__inner) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 修改上传组件中文件名的样式 */
:deep(.el-upload-list__item-name) {
  max-width: 300px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 调整上传列表的宽度 */
:deep(.el-upload-list) {
  width: 100%;
}

/* 确保上传区域不会超出对话框 */
:deep(.el-upload-dragger) {
  width: 100%;
}

/* 调整对话框内容的最大宽度 */
:deep(.el-dialog__body) {
  max-width: 100%;
  overflow: hidden;
}

/* 确保选择框样式保留 */
:deep(.el-table .el-table__row .el-table-column--selection .cell) {
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 40px;
}

:deep(.el-table__header .el-table-column--selection .cell) {
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 40px;
}

:deep(.el-table__header .el-checkbox) {
  margin: 0;
  padding: 0;
  display: flex;
  align-items: center;
  height: 100%;
}

:deep(.el-table__body .el-checkbox) {
  margin: 0;
  padding: 0;
  display: flex;
  align-items: center;
  height: 100%;
}

:deep(.el-checkbox__inner) {
  position: relative;
  top: 0;
}

.h-full {
  height: calc(100vh - 150px); /* 使用视窗高度减去头部和其他元素的高度 */
  background-color: #ffffff; /* 或者你想要的其他颜色 */
}

.h-full-list {
  height: calc(100vh - 278px); /* 使用视窗高度减去头部和其他元素的高度 */
  background-color: #ffffff; /* 或者你想要的其他颜色 */
  overflow-y: auto;
}
</style>
